##############################################################################
#
#    OmniaSolutions, Your own solutions
#    Copyright (C) 16/mar/2015 OmniaSolutions (<http://www.omniasolutions.eu>). All Rights Reserved
#    info@omniasolutions.eu
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
'''
Created on 16/mar/2015

@author: mboscolo
'''
import logging
#import logging.config
import os
from utils.utils            import getModulePath
fileLogPath = os.path.join(getModulePath(), 'tray_manager_log.log')
#logging.config.fileConfig(fileLogPath)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# ch = logging.StreamHandler()
# ch.setLevel(logging.DEBUG)
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# ch.setFormatter(formatter)
#logger.addHandler(ch)


import sys
from PyQt4                  import QtGui
from PyQt4                  import QtCore
from manager                import Manager
from utils.utils            import getIconsDirectory
from utils.utils            import convertJpgToPng
from utils                  import utils
from utils.utils            import getUsefulPath
from utils.utils            import launchTryIconMessage
from utils.utils            import computePath
from constants.constants    import TABLE_NAME_CONFIGURATIONS
from constants.constants    import ICON_SWITCH_1
from constants.constants    import ICON_SWITCH_2
from constants.constants    import ICON_SWITCH_0 
from constants.constants    import ICON_SPLASH
import psutil
import time

def kill_proc_tree(pid, including_parent=True):    
    parent = psutil.Process(pid)
    for child in parent.children(recursive=True):
        child.kill()
    if including_parent:
        parent.kill()


class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, tryParent=None, app=None):
        QtGui.QSystemTrayIcon.__init__(self, tryParent)
        self.tryParent = tryParent
        self.app = app
        iconsDir = getIconsDirectory()
        iniFile = os.path.join(os.path.expanduser('~'),'trayManager/trayManagerSettings.ini')
        self.settings       = QtCore.QSettings(iniFile, QtCore.QSettings.IniFormat)
        utils.TRY_ICON_OBJ = self
        self.launchSpashScreeen(iconsDir)
        mainJpgPath = computePath(os.path.join(iconsDir, ICON_SWITCH_0))
        self.setIcon(QtGui.QIcon(mainJpgPath))
        self.managerTimer = QtCore.QTimer(self)
        self.managerTimer.timeout.connect(self.initManager)
        self.managerTimer.setSingleShot(True)
        self.managerTimer.start(0.5)
        
    def launchChangeIcons(self):
        self.lastImageName = ICON_SWITCH_1
        self.iconsTimer = QtCore.QTimer(self)
        self.iconsTimer.timeout.connect(self.changeTryIconImage)
        self.iconsTimer.start(2)
        
    def verifyAllcomputed(self):
        continueThread = True
        if self.manager:
            objConfig = self.manager.dbInst.getRowsTable(TABLE_NAME_CONFIGURATIONS, ['config_value'], [('config_name', '=', 'EXE_SEARCH_PATH')])
            toCreateFiles = []
            for obj in objConfig:
                tmpVal = eval(obj.config_value)
                for fileName in tmpVal:
                    newName = os.path.basename(fileName)
                    toCreateFiles.append('exe_list_%s.txt' % (newName))
            usefulPath = getUsefulPath()
            files = os.listdir(usefulPath)
            createdFiles = []
            for fileName in files:
                if fileName.startswith('exe_list_'):
                    createdFiles.append(fileName)
            notCreated = [fileName for fileName in toCreateFiles if fileName not in createdFiles]
            if not notCreated:
                continueThread = False
                logging.info('All exe are searched.')
            #logging.info('Not created exe files: %s' % (notCreated))
        return continueThread
        
    def changeTryIconImage(self):
        continueThread = self.verifyAllcomputed()
        iconsDir = getIconsDirectory()
        if not continueThread:
            launchTryIconMessage('Tray Applications Manager Exe Search Finished', 'Tray Applications Manager Exe Search Ended.')
            self.iconsTimer.stop()
            self.iconsTimer.killTimer(1)
            self.iconsTimer.deleteLater()
            mainJpgPath = computePath(os.path.join(iconsDir, ICON_SWITCH_0))
            self.setIcon(QtGui.QIcon(mainJpgPath))
            return 
        else:
            localName = ICON_SWITCH_1
            if self.lastImageName == ICON_SWITCH_1:
                localName = ICON_SWITCH_1
                self.lastImageName = ICON_SWITCH_2
            elif self.lastImageName == ICON_SWITCH_2:
                localName = ICON_SWITCH_2
                self.lastImageName = ICON_SWITCH_1
            mainJpgPath = computePath(os.path.join(iconsDir,localName))
            time.sleep(0.5)
            mainImagePath = convertJpgToPng(mainJpgPath)
            self.setIcon(QtGui.QIcon(mainImagePath))
        
    def launchSpashScreeen(self, iconsDir):
        start = time.time()
        spashJpgImage = computePath(os.path.join(iconsDir, ICON_SPLASH))
        splashImage = convertJpgToPng(spashJpgImage)
        #logMessage(message='main: pixmapImage = %s' % (splashImage))
        splash_pix  = QtGui.QPixmap(splashImage)
        splash      = QtGui.QSplashScreen(splash_pix)
        splash.setMask(splash_pix.mask())
        splash.show()
        time.sleep(2)
        while time.time() - start < 1:
            time.sleep(0.001)
            self.app.processEvents()
        try:
            splash.finish(self.tryParent)
        except:
            pass

    def initManager(self):
        self.manager = Manager(self)
            
    def exit(self):
        """
            this is the exit action that close the try
        """
        self.manager.threads = []
        sys.stderr.write('\r')
        if QtGui.QMessageBox.question(None, '', "Are you sure you want to quit?",
                                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                                QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
            logging.info('Exit application')
            me = os.getpid()
            kill_proc_tree(me)
            return self.app.quit()

def main():
    app = QtGui.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    app.setStyle('plastique')
    w = QtGui.QWidget()
    trayIcon = SystemTrayIcon(w, app)

    trayIcon.show()
    app.exec_()

if __name__ == '__main__':
    main()
